<?php


namespace servers\cyf;


use servers\CurlServer;

//文本策略类
class TextFilter implements Filter
{

    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    /**
     * 获取token
     */
    public function getToken()
    {
        $apikey = 'wWzcZYoZjTZH15tuzRSPEVoV';
        $SecretKey = 'lVGAwGIlYltfAPdefYyW6NrGb1LcIgBo';
        $url = "https://aip.baidubce.com/oauth/2.0/token?client_id=$apikey&client_secret=$SecretKey&grant_type=client_credentials";
        $curl = new CurlServer();
        $response = $curl->post($url);
        return json_decode($response,true)['access_token'];
    }

    /**
     * 实现方法
     * @param $image
     * @return bool|string
     */
    public function content($text)
    {
        $token = $this->getToken();
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'text' => $text
        );
        $response = $this->request_post($url, $bodys);
        $responseArr = json_decode($response,true);
        if($responseArr['conclusion'] == '合规'){
            return true;
        }else{
            return $response;
        }


    }
}